import React, { useEffect, useState } from 'react';
import './App.css';
import EnergyMonitor from './components/EnergyMonitor';
import EnergyHistoryChart from './components/charts/EnergyHistoryChart';
import EnergyDistributionChart from './components/charts/EnergyDistributionChart';
import DigitalMap from './components/DigitalMap';
import AlertPanel from './components/AlertPanel';
import RealTimeMonitor from './components/RealTimeMonitor';
import IndicatorAnalysis from './components/IndicatorAnalysis';
import EventTrend from './components/EventTrend';
import Card from './components/Card';
import { getSceneList } from './api';
import { getAlarmDetails, getAlarmStatistics, getAlarmTrend, getDeviceConsumptionRatio, getDeviceStatus, getEnergySavingHistory, getMonthlyEnergyConsumption, getSceneMetric, getSceneMetricData } from './api/sceneBoard';
import LoginModal from './components/LoginModal';
import { getUserInfo } from './utils';
import moment from 'moment';
import dayjs from 'dayjs';

const App: React.FC = () => {
  const [isShowLoginModal, setIsShowLoginModal] = useState(localStorage.getItem('token') ? false : true)
  const [showLeftArrow, setShowLeftArrow] = useState(false);
  const [showRightArrow, setShowRightArrow] = useState(true);

  const [sceneList, setSceneList] = useState<any[]>([])
  const [energyData, setEnergyData] = useState<any>(null);
  const [alarmStatistics, setAlarmStatistics] = useState<any>(null);
  const [alarmDetail, setAlarmDetail] = useState<any>(null);
  const [analysisParams, setAnalysisParams] = useState<any>({
    start: dayjs().subtract(1, 'days').format('YYYY-MM-DD'),
    end: dayjs().format('YYYY-MM-DD')
  })
  const [currentSceneId, setCurrentSceneId] = useState<string>('')
  const [alarmPageNum, _setAlarmPageNum] = useState<number>(1)

  const getEnergyData = async (id: string) => {
    const res = await getMonthlyEnergyConsumption(id);
    setEnergyData(res.data);
  }

  // 告警统计
  const _getAlarmStatistics = async (id: string) => {
    const res = await getAlarmStatistics(id);
    setAlarmStatistics(res.data);
  }

  // 告警明细
  const _getAlarmDetail = async (id: string, pageNum?: number | undefined) => {
    console.log('_getAlarmDetail', id)
    const res = await getAlarmDetails(id, pageNum || alarmPageNum, 3);
    setAlarmDetail(res.data);
  }

  const setAlarmPageNum = (pageNum: number) => {
    _getAlarmDetail(currentSceneId, pageNum)
    _setAlarmPageNum(pageNum)
  }

  // 能耗占比
  const [deviceConsumptionRatio, setDeviceConsumptionRatio] = useState<any>(null);

  const _getAlarmDetailgetDeviceConsumptionRatio = async (id: string) => {
    const res = await getDeviceConsumptionRatio(id);
    setDeviceConsumptionRatio(res.data);
  }

  // 节能历史
  const [energyHistory, setEnergyHistory] = useState<any>(null);
  const _getEnergyHistory = async (id: string) => {
    const res = await getEnergySavingHistory(id);
    setEnergyHistory(res.data);
  }

  // 事件趋势
  const [eventTrend, setEventTrend] = useState<any>(null);
  const _getEventTrend = async (id: string) => {
    const res = await getAlarmTrend(id);
    setEventTrend(res.data);
  }

  // 设备情况
  const [deviceStatus, setDeviceStatus] = useState<any>(null);
  const _getDeviceStatus = async (id: string) => {
    const res = await getDeviceStatus(id);
    console.log('res', res)
    setDeviceStatus(res.data);
  }

  // 场景指标
  const [sceneMetric, setSceneMetric] = useState<any>(null);
  const _getSceneMetric = async (id: string) => {
    const res = await getSceneMetric(id);
    setSceneMetric(res.data?.content);
  }

  const [sceneMetricData, setSceneMetricData] = useState<any>(null);
  const [alarmData, setAlarmData] = useState<any>(null);
  const _getSceneMetricData = async (id: string) => {
    const data: any = {}
    const alarmData: any = {}
    for await (const metricId of analysisParams.metricIds) {
      const res = await getSceneMetricData({
        sceneId: id,
        metricId,
        dim: 'scene',
        start: analysisParams.start,
        endTime: analysisParams.end,
        valueType: 'avg',
        aggUnit: '10m'
      });

      // metricId 换 label
      const metric = sceneMetric.find((item: any) => item.id === metricId)
      data[metric.name] = res.data?.content?.[0]?.details;
      alarmData[metric.name] = res.data?.content?.[0]?.alarms
    }
    console.log('_getSceneMetricData', data, alarmData)
    setSceneMetricData(data);
    setAlarmData(alarmData)
  }

  const handleAnalysis = () => {
    _getSceneMetricData(currentSceneId)
  }

  const init = async () => {
    const res = await getSceneList()
    setSceneList(res.data?.content)

    const currentSceneId = res.data?.content[0].id
    setCurrentSceneId(currentSceneId)
    getEnergyData(currentSceneId)
    _getAlarmStatistics(currentSceneId)
    _getAlarmDetail(currentSceneId)
    _getAlarmDetailgetDeviceConsumptionRatio(currentSceneId)
    _getEnergyHistory(currentSceneId)
    _getEventTrend(currentSceneId)
    _getDeviceStatus(currentSceneId)
    _getSceneMetric(currentSceneId)
  }

  const changeScene = (id: string) => {
    getEnergyData(id)
    _getAlarmStatistics(id)
    _getAlarmDetail(id, 1)
    _getAlarmDetailgetDeviceConsumptionRatio(id)
    _getEnergyHistory(id)
    _getEventTrend(id)
    _getDeviceStatus(id)
    _getSceneMetric(id)
    setCurrentSceneId(id)

    setAnalysisParams({
      metricIds: [],
      start: moment().subtract(1, 'days').format('YYYY-MM-DD'),
      end: moment().format('YYYY-MM-DD')
    })
    setSceneMetricData({})
    _setAlarmPageNum(1)
  }

  useEffect(() => {
    init()
  }, [])

  // 处理导航栏左右滑动
  const handleNavScroll = (direction: 'left' | 'right') => {
    const navLinks = document.querySelector('.nav-links');
    if (navLinks) {
      const scrollAmount = 300; // 每次滚动的像素数
      const currentScroll = navLinks.scrollLeft;
      const maxScroll = navLinks.scrollWidth - navLinks.clientWidth;

      if (direction === 'left') {
        const newScrollLeft = Math.max(0, currentScroll - scrollAmount);
        navLinks.scrollLeft = newScrollLeft;
        setShowLeftArrow(newScrollLeft > 0);
        setShowRightArrow(true);
      } else {
        const newScrollLeft = Math.min(maxScroll, currentScroll + scrollAmount);
        navLinks.scrollLeft = newScrollLeft;
        setShowLeftArrow(true);
        setShowRightArrow(newScrollLeft < maxScroll);
      }
    }
  }

  // 监听导航栏滚动事件
  useEffect(() => {
    const navLinks = document.querySelector('.nav-links');
    if (navLinks) {
      const handleScroll = () => {
        const { scrollLeft, scrollWidth, clientWidth } = navLinks;
        setShowLeftArrow(scrollLeft > 0);
        setShowRightArrow(scrollLeft < scrollWidth - clientWidth - 5);
      };

      navLinks.addEventListener('scroll', handleScroll);
      // 初始检查
      handleScroll();

      return () => {
        navLinks.removeEventListener('scroll', handleScroll);
      };
    }
  }, [sceneList]);

  return (
    <div className="dashboard">
      <LoginModal visible={isShowLoginModal} onClose={() => { setIsShowLoginModal(false) }} />
      <header className="dashboard-header">
        <div className="header-content">
          <img src="/绿色管家logo@3x.png" alt="绿色管家" className="logo" />

          <div className='header-right'>
            <div className="nav-links-container">
              <div className={`nav-arrow nav-arrow-left ${!showLeftArrow ? 'hidden' : ''}`} onClick={() => handleNavScroll('left')}>
                <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" strokeWidth="2" fill="none">
                  <polyline points="15 18 9 12 15 6"></polyline>
                </svg>
              </div>
              <div className="nav-links">
                {sceneList.map((item) => (
                  <div className="nav-link" key={item.id} onClick={() => { changeScene(item.id) }}>{item.name}</div>
                ))}
              </div>
              <div className={`nav-arrow nav-arrow-right ${!showRightArrow ? 'hidden' : ''}`} onClick={() => handleNavScroll('right')}>
                <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" strokeWidth="2" fill="none">
                  <polyline points="9 18 15 12 9 6"></polyline>
                </svg>
              </div>
            </div>
            <div className="nav-separator">|</div>
            <div className="header-help">
              <img src="/问号@3x.png" alt="" style={{ width: '32px', height: 'auto' }} />
              帮助</div>
            <div className="header-user">
              <img src={"/用户头像@3x.png"} alt="" style={{ width: '50px', height: 'auto' }} />{getUserInfo().nickName}</div>

            <div className='header-user-logout' onClick={() => {
              localStorage.removeItem('token')
              window.location.reload()
            }}>退出</div>
          </div>

        </div>
        <img className='header-bg' src="/header.png" alt="" style={{ width: '160vw', height: 'auto', transform: 'translate(-30vw,-0px)' }} />

      </header>
      <main className="dashboard-content">
        <div className="left-panel">
          <EnergyMonitor energyData={energyData} />
          {/* <div className="content-card-base energy-history" > */}
          <EnergyHistoryChart energyHistory={energyHistory} />
          {/* </div> */}

        </div>
        <div className="center-panel">
          <DigitalMap deviceStatus={deviceStatus} />
          {/* <div className="monitor-analysis-container">
            <div className="content-card-base real-time-monitor">
              <Card title='实时画面' desc=''>
                <RealTimeMonitor />
              </Card>
            </div>
          </div> */}
        </div>
        <div className="right-panel">
          <div className="content-card-base right-panel-top">
            <Card title='告警事件' subTitle='Alarm ever' desc='（当天）'>
              <AlertPanel alarmPageNum={alarmPageNum} setAlarmPageNum={setAlarmPageNum} alarmStatistics={alarmStatistics} alarmDetail={alarmDetail} />
            </Card>
          </div>
          <div className="content-card-base right-panel-mid">
            <Card title='事件趋势' desc='' subTitle='Event Trend'>
              <EventTrend eventTrend={eventTrend} />
            </Card>
          </div>
          {/* <div className="content-card-base indicator-analysis">
            <Card title='指标分析' desc=''>
              <IndicatorAnalysis />
            </Card>
          </div> */}
        </div>
      </main>

      <div className='footer-panel'>
        <div className="content-card-base energy-distribution">
          <Card title='能耗占比' desc='（最近七天）' subTitle='Proportion of Energy Consumption'>
            <EnergyDistributionChart deviceConsumptionRatio={deviceConsumptionRatio} />
          </Card>
        </div>
        <div className="monitor-analysis-container">
          <Card bg={2} bgStyle={{ width: '101%' }} style={{ height: '100%' }} contentStyle={{ height: '100%' }}>
            <div className='monitor-analysis-container-content'>
              <RealTimeMonitor />
              <div className='line'></div>
              <IndicatorAnalysis alarmData={alarmData} sceneMetric={sceneMetric} params={analysisParams} onChange={setAnalysisParams} onAnalysis={handleAnalysis} sceneMetricData={sceneMetricData} />
            </div>
          </Card>
          {/* <Card title='实时画面' desc=''>
            <RealTimeMonitor />
          </Card>
          <Card title='指标分析' desc=''>
            <IndicatorAnalysis />
          </Card> */}
        </div>
      </div>

      <footer className="dashboard-footer">
        <div className="footer-content">
          {/* <pre>告警的指标<span className='red-label'>10分钟</span>聚合
            <br />
            指标时间段内告警<span className='red-label'>指标标红</span>
            <br />
            告警涉及多个指标，<span className='red-label'>时间段内同时标红</span></pre> */}
        </div>
      </footer>
    </div >
  );
};

export default App;
